package com.example.wangda.smart_home_android_v12;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.util.Log;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.TimeZone;

/**
 * Created by wangda on 2017/11/10.
 */

public class IFlytekTTS {
    Context context;
    private static final String TAG = "__IFlytekTTS__";
    String strWeather;
    IFlytekTTS(Context context){
        this.context = context;
    }

    //TTS
    private SpeechSynthesizer mTts;

    /*讯飞TTS*/
    public void tts_init()
    {
        // 将“12345678”替换成您申请的 APPID，申请地址： http://www.xfyun.cn
        // 请勿在“ =”与 appid 之间添加任务空字符或者转义符
        SpeechUtility.createUtility(context, SpeechConstant.APPID+"=58eaf86e");
        //1.创建 SpeechSynthesizer 对象, 第二个参数： 本地合成时传 InitListener
        mTts= SpeechSynthesizer.createSynthesizer(context, null);
        //2.合成参数设置，详见《 MSC Reference Manual》 SpeechSynthesizer 类
        //设置发音人（更多在线发音人，用户可参见 附录13.2
        mTts.setParameter(SpeechConstant.VOICE_NAME, "aisjiuxu"); //设置发音人
        mTts.setParameter(SpeechConstant.SPEED, "60");//设置语速
        mTts.setParameter(SpeechConstant.VOLUME, "100");//设置音量，范围 0~100
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
        //设置合成音频保存位置（可自定义保存位置），保存在“./sdcard/iflytek.pcm”
        //保存在 SD 卡需要在 AndroidManifest.xml 添加写 SD 卡权限
        //仅支持保存为 pcm 和 wav 格式， 如果不需要保存合成音频，注释该行代码
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "./sdcard/iflytek.pcm");
        //3.开始合成
        new Thread(new thread_voice()).start();
    }

    //合成监听器
    private SynthesizerListener mSynListener = new SynthesizerListener(){
        //会话结束回调接口，没有错误时， error为null
        public void onCompleted(SpeechError error) {
            if(error != null){
                //MainActivity.Log_out("语音播报出错，错误代码：" + error);
                Log.d(TAG, "语音播报出错，错误代码：" + error);
            }else{
                //MainActivity.Log_out("语音转换完整");
                Log.d(TAG, "语音转换完整");
            }
        }
        //缓冲进度回调
        //percent为缓冲进度0~100， beginPos为缓冲音频在文本中开始位置， endPos表示缓冲音频在
        // 文本中结束位置， info为附加信息。
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {}
        //开始播放
        public void onSpeakBegin() {}
        //暂停播放
        public void onSpeakPaused() {}
        //播放进度回调
        //percent为播放进度0~100,beginPos为播放音频在文本中开始位置， endPos表示播放音频在文
        //本中结束位置.
        public void onSpeakProgress(int percent, int beginPos, int endPos) {}
        //恢复播放回调接口
        public void onSpeakResumed() {}
        //会话事件回调接口
        public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {}
        public void onError(SpeechError error) {
            MainActivity.Log_out(error.toString());
        }
    };

    /*
    *语音播报
    * @return
     */
    public void startSpeaking(String str)
    {
        if(GlobalData.ReadMuaicPlayClock() != GlobalData.Clock) {
            mTts.startSpeaking(str, mSynListener);
        }
    }

    //class handle
    //语音处理
    class thread_voice implements Runnable{
        int hour_tmp=0;
        @Override
        public void run(){

            while(true){
                try{
                    Calendar cal = Calendar.getInstance();
                    cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                    int hour = cal.get(Calendar.HOUR_OF_DAY);
                    int min = cal.get(Calendar.MINUTE);
                    if(hour == 7 && min == 0 && hour_tmp != 7)
                    {
                        GlobalData.SetMusicPlayClock(GlobalData.unClock);
                        startSpeaking("现在是，早上7点钟，早上好");
                        Thread.sleep(6000);
                        reportWeather();
                        Thread.sleep(6000);
                        localPlayBack();
                        hour_tmp = hour;
                        Log.d(TAG, "7点语音播放");
                    }
                    if(hour==9 && min == 0 && hour_tmp != 9)
                    {
                        startSpeaking("现在是，早上9点钟，早上好");
                        hour_tmp = hour;
                        Log.d(TAG, "9点语音播放");
                    }
                    if(hour==11 && min == 0 && hour_tmp != 11)
                    {
                        startSpeaking("现在是，11点钟");
                        hour_tmp = hour;
                        Log.d(TAG, "11点语音播放");
                    }
                    if(hour==13 && min == 0 && hour_tmp != 12)
                    {
                        startSpeaking("现在是，下午1点钟，下午好");
                        Thread.sleep(6000);
                        reportWeather();
                        Thread.sleep(6000);
                        localPlayBack();
                        hour_tmp = hour;
                        Log.d(TAG, "13点语音播放");
                    }
                    if(hour==16 && min == 0 && hour_tmp != 16)
                    {
                        startSpeaking("现在是，下午4点钟，下午好");
                        hour_tmp = hour;
                        Log.d(TAG, "16点语音播放");
                    }
                    if(hour==18 && min == 0 && hour_tmp != 18)
                    {
                        startSpeaking("现在是，傍晚6点钟，晚上好");
                        hour_tmp = hour;
                        Log.d(TAG, "18点语音播放");
                    }
                    if(hour==19 && min == 0 && hour_tmp != 19)
                    {
                        startSpeaking("现在是，晚上7点钟");
                        hour_tmp = hour;
                        Log.d(TAG, "19点语音播放");
                    }
                    if(hour==21 && min == 0 && hour_tmp != 21)
                    {
                        startSpeaking("现在是晚上9点钟，至次日7点暂停所有语音播放");
                        Thread.sleep(6000);
                        reportWeather();
                        Thread.sleep(6000);
                        localPlayBack();
                        hour_tmp = hour;
                        Log.d(TAG, "21点语音播放");
                        GlobalData.SetMusicPlayClock(GlobalData.Clock);
                    }
                    Thread.sleep(50000);
                }catch(Exception e){
                    Log.d(TAG, "catch = " + e);
                }
            }
        }
    }

    //获取JSON数据
    //return : 0-success 1-error
    private byte getJsonData()
    {
        String rcvData="";
        String str="";
        try
        {
                URL url = new URL("https://www.sojson.com/open/api/weather/json.shtml?city=%e5%ae%81%e6%b3%a2");
                /*https证书解决方案*/
                if("https".equalsIgnoreCase(url.getProtocol())){
                    SslUtils.ignoreSsl();
                }
                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                while ((str = in.readLine()) != null) {
                    rcvData += str;
                }
                in.close();

                JSONObject jsonObject=new JSONObject(rcvData);
                String data = jsonObject.getString("data");

                JSONObject jsonObject1=new JSONObject(data);
                JSONArray jsonArray = jsonObject1.getJSONArray("forecast");

                JSONObject jsonObject3 = (JSONObject)jsonArray.opt(0);
                String str1 = jsonObject3.getString("date");

                JSONObject jsonObject4 = (JSONObject)jsonArray.opt(1);
                JSONObject jsonObject5 = (JSONObject)jsonArray.opt(2);

                strWeather = "今天是：" + jsonObject3.getString("date")+ ";" + "今天天气：" + jsonObject3.getString("type") + ";" + jsonObject3.getString("fx") + jsonObject3.getString("fl")  + ";" + jsonObject3.getString("high") + ";" + jsonObject3.getString("low") +  ";当前温度：" + jsonObject1.getString("wendu") +"℃"+ ";当前湿度："+ jsonObject1.getString("shidu")+ ";" +jsonObject3.getString("notice") + ";"
                        + "PM2.5指数：" + jsonObject1.getString("pm25") + ";PM10指数：" + jsonObject1.getString("pm10") + ";" + jsonObject1.getString("quality") + ";"+ jsonObject1.getString("ganmao")
                        + ";明天" + jsonObject4.getString("date") + ";天气;" + jsonObject4.getString("type") + ";" +jsonObject4.getString("fx") + jsonObject4.getString("fl") + ";" +jsonObject4.getString("high") + ";" + jsonObject4.getString("low") + ";" + jsonObject4.getString("notice")
                        + ";后天"+  jsonObject5.getString("date") + ";天气;" + jsonObject5.getString("type") + ";" +jsonObject5.getString("fx") + jsonObject5.getString("fl") + ";" +jsonObject5.getString("high") + ";" + jsonObject5.getString("low") + ";" + jsonObject5.getString("notice");
        }catch(Exception e)
        {
            Log.d(TAG, e.toString());
            return 1;
        }
        return 0;
    }
    /*播放欢迎光临*/
    public void localPlayWelcome()
    {
        if(GlobalData.ReadMuaicPlayClock() != GlobalData.Clock) {
            MediaPlayer player  =  MediaPlayer.create(context,R.raw.welcome);
            player.start();
        }
    }
    /*播放背景音乐*/
    public void localPlayBack()
    {
        if(GlobalData.ReadMuaicPlayClock() != GlobalData.Clock) {
            MediaPlayer player  =  MediaPlayer.create(context,R.raw.richardclayderman);
            player.start();
        }
    }

    //播报天气
    public void reportWeather()
    {
        if(getJsonData() == 0){
            mTts.startSpeaking(strWeather, mSynListener);
        }
        else
        {
            mTts.startSpeaking("天气数据获取出错，请检查网络", mSynListener);
        }
    }
}
